package com.urbanski.clipboard.server.action.message;

import java.io.IOException;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.common.message.LeaveMessage;
import com.urbanski.clipboard.common.message.LeaveResponse;
import com.urbanski.clipboard.common.message.LeaveResponse.LeaveResponseValue;
import com.urbanski.clipboard.common.message.Message;
import com.urbanski.clipboard.server.ClientSocket;
import com.urbanski.clipboard.server.ClipboardServer;
import com.urbanski.clipboard.server.session.ServerSession;
import com.urbanski.util.logging.LoggingUtil;

public class LeaveMessageHandler extends ServerMessageHandler
{
	private static final Logger LOGGER = Logger.getLogger(LeaveMessageHandler.class);

	public LeaveMessageHandler(ClientSocket client)
	{
		super(client);
	}

	@Override
	public void handle(Message message)
	{
		LeaveMessage leaveMessage = (LeaveMessage)message;

		ServerSession session = ClipboardServer.getSession(leaveMessage.getSessionName());
		LeaveResponse response;

		if (session == null)
		{
			response = new LeaveResponse(LeaveResponseValue.SESSION_DOES_NOT_EXIST);
		}
		else
		{
			synchronized (session)
			{
				if (session.getClients().get(client.getClientName()) == null)
				{
					response = new LeaveResponse(LeaveResponseValue.NOT_MEMBER);
				}
				else
				{
					session.removeClient(client);
					response = new LeaveResponse(LeaveResponseValue.SUCCESS);

					if (session.getClients().size() == 0)
					{
						LOGGER.info("Last client left session " + session.getSessionName());
						ClipboardServer.removeSession(session.getSessionName());
					}
				}
			}
		}

		System.out.println("Session leave response: " + response.getResponseText());

		try
		{
			client.sendResponse(response);
		}
		catch (IOException e)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Error sending response", e);
		}
	}

}
